package com.dgutnw.yeziyin.sbexp.exp03_covid19_realtimedate.controllers;

import com.dgutnw.yeziyin.sbexp.exp03_covid19_realtimedate.models.RegionStats;
import com.dgutnw.yeziyin.sbexp.exp03_covid19_realtimedate.services.Covid19DateService;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.stream.Collectors;

@Controller
@Data
public class HomeController {

    @Autowired
    Covid19DateService covid19DateService;
    int latestTotalCases;
    int diffFromPrevDayTotal;

    @RequestMapping("/")
    public String getAllRegionStats(HttpServletRequest request, HttpServletResponse response,Model model)throws ServletException, IOException{
        List<RegionStats> RS=covid19DateService.getRegionStatsList();
        Date TimeAtNow = new Date();

        latestTotalCases= RS.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        diffFromPrevDayTotal= RS.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("regionStats",RS);
        model.addAttribute("datenow",TimeAtNow);
        model.addAttribute("totalReportCases",latestTotalCases);
        model.addAttribute("totalNewCases",diffFromPrevDayTotal);

        System.out.println("last:"+latestTotalCases);
        return "index";
    }
    @RequestMapping("/{countryn}")
    public String SearchCountry(Model model, @PathVariable("countryn") String country)
    {
        List<RegionStats> RS ;

        if(country == null || country.equals("all")){
            RS= covid19DateService.getRegionStatsList();
        }
        else{//将查询结果收集为不可变的List集合
            RS = covid19DateService.getRegionStatsList()
                    .parallelStream().filter(locationStats -> locationStats.getCountry().equals(country))
                    .collect(Collectors.toUnmodifiableList());
        }

        Date TimeAtNow = new Date();


        //求和
        latestTotalCases= RS.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        diffFromPrevDayTotal= RS.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("country",country);
        model.addAttribute("regionStats",RS);
        model.addAttribute("datenow",TimeAtNow);
        model.addAttribute("totalReportCases",latestTotalCases);
        model.addAttribute("totalNewCases",diffFromPrevDayTotal);

        System.out.println("last:"+latestTotalCases);
        return "index";
    }

}
